package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.BrandDao;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.eq("brand_id", key).or().likeRight("name", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }
    
    /**
     * 修改品牌时，修改关联关系
     */
    @Override
    public void updateDetail(BrandEntity brand) {
        if (StringUtils.isNotEmpty(brand.getName())) {
            //修改品牌与分类关联关系表
            categoryBrandRelationService.updateByBrandName(brand.getBrandId(),brand.getName());
            //TODO 修改其他关联关系
        }
        //修改品牌
        updateById(brand);
    }
    
    
    /**
     * 根据品牌Ids获取品牌集合
     */
    @Override
    public List<BrandEntity> getBrandsByIds(List<Long> brandIds) {
        return this.list(new LambdaQueryWrapper<BrandEntity>().in(BrandEntity::getBrandId,brandIds));
    }
    
}